{% extends "tools/base_tool.html" %}

{% block title %}文档搜索{% endblock %}

{% block styles %}
<link rel="stylesheet" href="/static/css/document-search.css">
{% endblock %}

{% block content %}
<div class="container document-search-container">
  <div class="search-container mb-3 d-flex justify-content-between align-items-center">
    <div class="search-input-wrapper position-relative flex-grow-1">
      <input type="text" id="search-input" class="form-control" placeholder="输入关键词搜索文档...">
      <i data-feather="search" class="search-icon"></i>
    </div>
    <button type="button" class="btn btn-primary ms-2" data-bs-toggle="modal" data-bs-target="#uploadDocModal">
      <i data-feather="upload"></i> 上传文档
    </button>
  </div>
  </div>
  
  <div id="loading-indicator">
    <div class="spinner-border text-primary" role="status">
      <span class="visually-hidden">加载中...</span>
    </div>
    <p>正在加载文档列表...</p>
  </div>
  
  <div id="error-message"></div>
  
  <div id="doc-list" class="doc-list"></div>
  
  <!-- 上传文档模态框 -->
  <div class="modal fade" id="uploadDocModal" tabindex="-1" aria-labelledby="uploadDocModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="uploadDocModalLabel">上传Markdown文档</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
        </div>
        <div class="modal-body">
          <form id="uploadDocForm" enctype="multipart/form-data">
            <div class="mb-3">
              <label for="docFile" class="form-label">选择Markdown文件</label>
              <input type="file" class="form-control" id="docFile" name="file" accept=".md" required>
              <div class="form-text">只支持.md格式的Markdown文件</div>
            </div>
            <div class="mb-3">
              <label for="docTitle" class="form-label">文档标题（可选）</label>
              <input type="text" class="form-control" id="docTitle" name="title" placeholder="如不填写，将使用原文件名">
            </div>
          </form>
          <div id="uploadStatus" class="alert alert-info d-none"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="submitUpload">上传</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    // 初始化Feather图标
    feather.replace();
    
    // 显示加载指示器
    const loadingIndicator = document.getElementById('loading-indicator');
    const errorMessage = document.getElementById('error-message');
    const docList = document.getElementById('doc-list');
    searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    
    loadingIndicator.style.display = 'block';
    docList.style.display = 'none';
    
    // 处理文档上传
    const uploadForm = document.getElementById('uploadDocForm');
    const submitUploadBtn = document.getElementById('submitUpload');
    const uploadStatus = document.getElementById('uploadStatus');
    const uploadModal = document.getElementById('uploadDocModal');
    const modalInstance = new bootstrap.Modal(uploadModal);
    
    submitUploadBtn.addEventListener('click', async function() {
      // 获取表单数据
      const formData = new FormData(uploadForm);
      const fileInput = document.getElementById('docFile');
      
      // 验证文件选择
      if (!fileInput.files || fileInput.files.length === 0) {
        showUploadStatus('请选择要上传的Markdown文件', 'danger');
        return;
      }
      
      // 验证文件类型
      const file = fileInput.files[0];
      if (!file.name.endsWith('.md')) {
        showUploadStatus('只支持上传.md格式的Markdown文件', 'danger');
        return;
      }
      
      // 显示上传中状态
      submitUploadBtn.disabled = true;
      showUploadStatus('正在上传文档...', 'info');
      
      try {
        // 发送上传请求
        const response = await fetch('/api/documentation/upload', {
          method: 'POST',
          body: formData
        });
        
        const result = await response.json();
        
        if (response.ok) {
          // 上传成功
          showUploadStatus(result.message || '文档上传成功', 'success');
          
          // 3秒后关闭模态框并刷新文档列表
          setTimeout(() => {
            modalInstance.hide();
            // 重置表单
            uploadForm.reset();
            // 刷新文档列表
            loadDocuments();
          }, 3000);
        } else {
          // 上传失败
          showUploadStatus(result.detail || '文档上传失败', 'danger');
        }
      } catch (error) {
        console.error('上传文档出错:', error);
        showUploadStatus('上传过程中发生错误，请重试', 'danger');
      } finally {
        submitUploadBtn.disabled = false;
      }
    });
    
    // 显示上传状态信息
    function showUploadStatus(message, type) {
      uploadStatus.textContent = message;
      uploadStatus.className = `alert alert-${type}`;
      uploadStatus.classList.remove('d-none');
    }
    
    // 模态框关闭时重置表单和状态
    uploadModal.addEventListener('hidden.bs.modal', function() {
      uploadForm.reset();
      uploadStatus.classList.add('d-none');
    });
    
    // 加载文档列表
    function loadDocuments(searchTerm = '') {
      loadingIndicator.style.display = 'block';
      docList.style.display = 'none';
      errorMessage.style.display = 'none';
      
      // 调用API获取文档列表
      fetch('/api/documentation/list')
        .then(response => {
          if (!response.ok) {
            throw new Error('文档列表加载失败，请稍后重试');
          }
          return response.json();
        })
        .then(data => {
          // 隐藏加载指示器
          loadingIndicator.style.display = 'none';
          docList.style.display = 'block';
          
          // 获取文档列表
          const documents = data.documents || [];
          
          // 如果有搜索词，过滤文档
          let filteredDocs = documents;
          if (searchTerm) {
            const term = searchTerm.toLowerCase();
            filteredDocs = documents.filter(doc => 
              doc.title.toLowerCase().includes(term)
            );
          }
          
          // 显示文档列表
          if (filteredDocs.length > 0) {
            docList.innerHTML = filteredDocs.map((doc, index) => `
              <div class="doc-item-x">
                <div class="flex-container">
                  <div class="doc-title">${doc.title}</div>
                  <div class="doc-actions">
                    <a href="/doc/${encodeURIComponent(doc.id)}" class="btn btn-primary btn-sm">
                      <i data-feather="book-open"></i> 查看
                    </a>
                  </div>
                </div>
              </div>
              ${index !== filteredDocs.length - 1 ? '<hr class="doc-divider">' : ''}
            `).join('');
            
            // 重新初始化图标
            feather.replace();
          } else {
            docList.innerHTML = `
              <div class="no-results">
                <i data-feather="search" class="search-icon-large"></i>
                <p>${searchTerm ? '没有找到匹配的文档' : '暂无文档'}</p>
              </div>
            `;
            feather.replace();
          }
        })
        .catch(error => {
          // 显示错误信息
          loadingIndicator.style.display = 'none';
          errorMessage.style.display = 'block';
          errorMessage.textContent = error.message;
          console.error('文档列表加载错误:', error);
          
          // 添加重试按钮
          errorMessage.innerHTML = `
            <p>${errorMessage.textContent}</p>
            <button class="btn btn-primary mt-2" onclick="loadDocuments()">
              重新加载
            </button>
          `;
        });
    }
    
    // 初始加载文档列表
    loadDocuments();
    
    // 搜索功能
    // 移除对search-btn的引用
    searchInput = document.getElementById('search-input');
    
    // 将搜索功能直接绑定到输入框的input事件
    searchInput.addEventListener('input', function() {
      const searchTerm = this.value.trim();
      loadDocuments(searchTerm);
    });
    
    // 回车键搜索
    searchInput.addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        const searchTerm = searchInput.value.trim();
        loadDocuments(searchTerm);
      }
    });
  });
</script>
{% endblock %}